package com.gongjie.blog.handler;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.gongjie.blog.dao.pojo.SysUser;
import com.gongjie.blog.admin.service.LoginService;
import com.gongjie.blog.utils.UserThreadLocal;
import com.gongjie.blog.vo.ErrorCode;
import com.gongjie.blog.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author jiegong
 * @create 2021-09-26 9:58
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private LoginService loginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在执行controller方法（Handler）之前进行执行
        /**
         * 1。 判断请求接口路径是否为HandlerMethod（controller方法）
         * 2. 判断token是否为空， 如果为空：未登录
         * 3. token不为空， 登录验证， loginService checkToken
         * 4. 认证成功： 放行
         */
        //1。 判断请求接口路径是否为HandlerMethod（controller方法） 可能是访问的静态资源
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //2. 判断token是否为空， 如果为空：未登录
        String token = request.getHeader("Authorization");

        log.info("=================request start===========================");
        String requestURI = request.getRequestURI();
        log.info("request uri:{}",requestURI);
        log.info("request method:{}",request.getMethod());
        log.info("token:{}", token);
        log.info("=================request end===========================");

        if (StringUtils.isBlank(token)) {
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), "未登录");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        //3. token不为空， 登录验证， loginService checkToken
        SysUser sysUser = loginService.checkToken(token);
        if (sysUser == null) {
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), "未登录");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        //4. 认证成功： 放行
        // 在controller中 可以直接获取用户信息
        UserThreadLocal.put(sysUser);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 不删除threadLocal中用完的信息， 会有内存泄露风险
        UserThreadLocal.remove();
    }
}
